'use strict'

module.exports = (function(){
    var params = require('../../config/params');
    var loggers = require('../lib/loggers');
    var util = require('util');
    var uuid = require('node-uuid');

    var output = loggers.output;
    var sessions = {}

    function getSession(token) {
        if ( !(token in sessions) ) {
            return {}
        }

        var sessionRecord = sessions[token];
        var session = sessionRecord.session;
        var currentEpoch = (new Date()).getTime();
        if ( currentEpoch > sessionRecord.expired ) {
            var user = session.login.user;

            output.info(util.format('Remove expired token of user %s', user.name));
            delete sessions[token];
            return {};
        }

        return session;
    }

    function removeToken(req, user) {
        req.session = {}
    }

    function newToken(req, user) {
        removeToken(req, user);

        var token = uuid.v4();
        output.info(util.format('Generate token %s for user %s',
                    token, user.name));

        let sessionRecord = {
            expired: (new Date()).getTime() + params.user.token.expired * 60 * 1000,
            session: {}
        };
        sessions[token] = sessionRecord;

        req.session = sessionRecord.session;

        return token;
    }

    function filter(req, res, next) {
        let token = null;

        if ( 'token' in req.query ) {
            token = req.query.token;
        }
        else if ( 'token' in req.cookies ) {
            token = req.cookies.token;
        }
        console.log(token);

        if ( token != null ) {
            req.session = getSession(token);
        }
        else {
            req.session = {}
        }

        next();
    }

    function isValid(token) {
        return (token in sessions);
    }

    return {
        filter: filter,
        newToken: newToken,
        removeToken: removeToken,
        isValid: isValid
    };
}());
